package com.saltedfish.tool.present;


import android.app.Activity;
import android.content.Context;

import com.google.gson.Gson;
import com.saltedfish.tool.constant.StringConstant;
import com.saltedfish.tool.dialog.LoadingDialogs;
import com.saltedfish.tool.model.LoginInfo;
import com.saltedfish.tool.model.ThirdLoginInfo;
import com.saltedfish.tool.model.User;
import com.saltedfish.tool.net.Api;
import com.saltedfish.tool.net.HttpUrls;
import com.saltedfish.tool.ui.user.LoginActivity;
import com.saltedfish.tool.util.SharePreferceUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;

import cn.droidlover.xdroidmvp.BaseApplication;
import cn.droidlover.xdroidmvp.bean.BaseModel;
import cn.droidlover.xdroidmvp.log.XLog;
import cn.droidlover.xdroidmvp.mvp.XPresent;
import cn.droidlover.xdroidmvp.net.ApiSubscriber;
import cn.droidlover.xdroidmvp.net.NetError;
import cn.droidlover.xdroidmvp.net.XApi;
import cn.droidlover.xdroidmvp.popwindow.LoadingDialog;
import cn.droidlover.xdroidmvp.util.AppUtil;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

public class LoginAP extends XPresent<LoginActivity> {

    /**
     *
     */
    public void login(ThirdLoginInfo login){

        Gson gson = new Gson();
        String postInfoStr = gson.toJson(login);
        RequestBody body = RequestBody.create(
                MediaType.parse("application/json; charset=utf-8"),
                postInfoStr
        );

        Api.getDyService().login(body)
                .compose(XApi.getApiTransformer())
                .compose(XApi.getScheduler())
                .compose(getV().bindToLifecycle())
                .subscribe(new ApiSubscriber<BaseModel<LoginInfo>>() {
                    @Override
                    protected void onFail(NetError error) {
                    }
                    @Override
                    public void onNext(BaseModel<LoginInfo> result) {
                        XLog.e("wx Info", "-wx Info----"+result.toString());
                        if(result.code == 200 ){
                            User.getInstance().loginSuccess(result.result);
                            getV().loginSuccess(result.result.userInfo);
                        }
                    }
                });
    }


//    /**
//     * 上传文件
//     *
//     * @param filePath
//     */
//    public void uploadFile(String filePath) {
//        File file = new File(filePath);
//        RequestBody body = RequestBody.create(MediaType.parse("multipart/form-data"), file);
//        MultipartBody multipartBody = new MultipartBody.Builder()
//                .setType(MultipartBody.FORM)
//                .addFormDataPart("file", file.getName(), body)
//                .build();
//
//        Api.getDyService().uploadFile(multipartBody.part(0))
//                .compose(XApi.getApiTransformer())
//                .compose(XApi.getScheduler())
//                .compose(getV().bindToLifecycle())
//                .subscribe(new ApiSubscriber<BaseModel<ModelInfo>>() {
//                    @Override
//                    protected void onFail(NetError error) {
//                    }
//                    @Override
//                    public void onNext(BaseModel<ModelInfo> result) {
//                        XLog.e("wx Info", "-wx uploadFile----"+result.toString());
//                        if(result.code == 200 ){
////                            User.getInstance().loginSuccess(result.result);
////                            getV().loginSuccess(result.result.userInfo);
//                        }
//                    }
//                });
//
//    }


    private  OkHttpClient okHttpClient;

    /**
     * @param
     * @param
     * @param
     * @param
     */

    public void downloadFile(Activity context) {
        //储存下载文件的目录


        String url = Api.API_BASE_URL + HttpUrls.DOWNLOAD_FILE;
       // String url = "https://v83.douyinvod.com/fe2a052250800568cb240c51d044c935/623a93ad/video/tos/cn/tos-cn-ve-15-alinc2/cc3e5d3ee5c648c6a32da72d11ca1d18/?a=1128&br=3105&bt=3105&cd=0%7C0%7C0%7C0&ch=0&cr=0&cs=0&cv=1&dr=0&ds=3&er=&ft=YbbdSWWFBiwqka4kagD12fezQd3w&l=202203231027350102091370354532E78E&lr=&mime_type=video_mp4&net=0&pl=0&qs=0&rc=M3Fmbjw6ZmQzOzMzNGkzM0ApZjM3ODo3ODw3N2VkZTw1OmcpaGRqbGRoaGRmMWtoZ3I0MGdlYC0tZC0wc3MvL2FhMi0vNGNhLzExMGAyOmNwb2wrbStqdDo%3D&vl=&vr=";
       // String url = "https://v5.douyinvod.com/6554ef67dbcfdf90a953101f8e128c67/62287e31/video/tos/cn/tos-cn-ve-15-alinc2/a17840a06db44dfb8bc4c0b1222ce500/?a=1128&br=1051&bt=1051&cd=0%7C0%7C0%7C0&ch=0&cr=0&cs=0&cv=1&dr=0&ds=3&er=&ft=YbbdSWWFBiwqka4kagD123x_Sd3w&l=202203091715050102120980974504E1BD&lr=&mime_type=video_mp4&net=0&pl=0&qs=0&rc=anRkOTc6ZjZpOzMzNGkzM0ApOWZnNTs6OWQzNzZoN2k5PGcpaGRqbGRoaGRmZW4tbHI0Z2lhYC0tZC1hc3NhX18wLS8xLjMwMmBeLS8tOmNwb2wrbStqdDo%3D&vl=&vr=";
        okHttpClient = new OkHttpClient();
        String token = SharePreferceUtils.getString(User.USER_TOKEN);
        String userId = SharePreferceUtils.getString(User.USER_ID);

        Request request = new Request.Builder()
                .url(url)
                .get()
                .header("c-token", token)
                .header("c-user-id", userId)
                .header("version-name", AppUtil.getVersionName(BaseApplication.getInstance()))
                .build();

        //异步请求
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // 下载失败监听回调
                XLog.e("下载失败监听回调，", e.toString());
               // LoadingDialogs.getInstance(context).dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                getResponseBody(response);
            }
        });
    }

    public void updateResponse(Response response) {
        InputStream is = null;
        byte[] buf = new byte[4 * 1024];
        int len = 0;
        FileOutputStream fos = null;
        try {
            File dir = new File(StringConstant.STORAGE_DIR);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File file = new File(dir, StringConstant.DbBase);

            is = response.body().byteStream();
            long total = response.body().contentLength();
            fos = new FileOutputStream(file);
            long sum = 0;
            while ((len = is.read(buf)) != -1) {
                fos.write(buf, 0, len);
                sum += len;
                int progress = (int) (sum * 1.0f / total * 100);
                //下载中更新进度条
                XLog.e("下载成功，progress-->>"+ progress);

            }
            fos.flush();
            getV().downloadFileSuccess(true);
            //下载完成
        } catch (Exception e) {
        } finally {

            try {
                if (is != null) {
                    is.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {

            }

        }


    }


    public void getResponseBody(Response response) {
        Charset UTF8 = Charset.forName("UTF-8");
        ResponseBody responseBody = response.body();
        BufferedSource source = responseBody.source();
        XLog.e("下载监听回1111111调成功，"+ source.toString());

        try {
            source.request(Long.MAX_VALUE); // Buffer the entire body.
        } catch (IOException e) {
            e.printStackTrace();
        }
        Buffer buffer = source.buffer();

        Charset charset = UTF8;
        MediaType contentType = responseBody.contentType();
        XLog.e("下载监听回contentType调成功，"+ contentType);

        if (contentType != null) {
            XLog.e("下载监听回contentType调成功222，"+ contentType.toString());

            if(contentType.toString().contains("download")){
                updateResponse(response);
            }else {
                getV().downloadFileSuccess(false);
//                try {
//                    charset = contentType.charset(UTF8);
//                    XLog.e("下载监听回33charset3333t调成功，"+charset);
//                } catch (UnsupportedCharsetException e) {
//                    XLog.e("下载监听回333333t调成功，"+e);
//                    e.printStackTrace();
//                }

//                String str = buffer.clone().readString(charset);
//                XLog.e("下载监听回charset调成功，"+ buffer.clone().readString(charset));

            }

        }

    }
}
